package com.study.d016event;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
*@description 拖拽按钮
*@author xtayhame
*date 2020年3月8日
*version
*since v1.0
*/
public class DragButtonMain extends Application{
	public double x=0;
	public double y=0;

	public static void main(String[] args) {
		launch(args);
	}
	@Override
	public void start(Stage stage) throws Exception {
		AnchorPane anchorPane = new AnchorPane();
		Button b1 =new Button("拖动按钮");

		anchorPane.getChildren().add(b1);

		AnchorPane.setTopAnchor(b1, 100.0);
		AnchorPane.setLeftAnchor(b1, 100.0);

		Scene scene = new Scene(anchorPane, 500, 600);
		stage.setScene(scene);
		stage.show();

		//当鼠标按下时触发
		b1.setOnMousePressed(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
				System.out.println("被点击了");
				x= event.getX();
				y= event.getY();
				System.out.println("x=" + event.getX() + "   y="+event.getY());
			}
		});

		b1.setOnMouseDragged(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {
				AnchorPane.setTopAnchor(b1, event.getSceneY() - y);
				AnchorPane.setLeftAnchor(b1, event.getSceneX() - x);
			}
		});
	}


}
